﻿using EduCommon;
using EduModel;
using System.Linq;
using System.Web.Mvc;

namespace EduCenter.Controllers
{
    public class AccountController : Controller
    {
        [AllowAnonymous]
        public ActionResult Login(string ReturnUrl)
        {
            ViewBag.returnUrl = ReturnUrl;
            if (CurUser.User != null)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(string username, string password, string checkcode)
        {
            if (!Request.IsAjaxRequest())
            {
                return View();
            }
            string sessionCode = Session["checkcode"].ToString();
            if (sessionCode.ToLower() != checkcode.ToLower())
            {
                return Json(new { status = Result.fail, message = "验证码错误！" });
            }
            else
            {
                using (EduContext db = new EduContext())
                {
                    password = MD5.Md5Hash(password).ToUpper();
                    T_User user = db.T_User.SingleOrDefault(t => t.LoginName.Equals(username));
                    if (user == null)
                    {
                        return Json(new { status = Result.fail, message = "用户名不存在！" });
                    }
                    else
                    {
                        user = db.T_User.SingleOrDefault(t => t.LoginName.Equals(username) && t.Password.Equals(password));
                        if (user == null)
                        {
                            return Json(new { status = Result.fail, message = "密码错误！" });
                        }
                        else
                        {
                            FormsAuth.SignIn(user.UserId.ToString(), user);
                            return Json(new { status = Result.success, jumpUrl = ViewBag.returnUrl ?? "/Home/Index" });
                        }
                    }
                }
            }
        }

        [AllowAnonymous]
        public ActionResult LogOut()
        {
            FormsAuth.SignOut();
            return RedirectToAction("Login");
        }

        [AllowAnonymous]
        public ActionResult GetCheckCode()
        {
            VerificationCode vh = new VerificationCode();
            string code = vh.GetRandomNumberString(4);
            Session["checkcode"] = code;
            byte[] img = vh.CreateImage(code);
            return File(img, "image/jpeg");
        }
    }
}